package com.xiaoxie.cloud.service.impl;

import com.xiaoxie.cloud.apis.AccountFeignApi;
import com.xiaoxie.cloud.apis.StorageFeignApi;
import com.xiaoxie.cloud.entities.Order;
import com.xiaoxie.cloud.mapper.OrderMapper;
import com.xiaoxie.cloud.service.OrderService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

@Service
@Slf4j
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;
    private final AccountFeignApi accountFeignApi;
    private final StorageFeignApi storageFeignApi;

    @Override
    // 最好是把这个注解的name属性加上
    @GlobalTransactional(name="xiaoxie-create-order",rollbackFor = Exception.class) // AT模式
    public void create(Order order) {
        // xid全局事务id的检查 ！！
        String xid = RootContext.getXID();
        // 1.新建订单
        log.info("------------开始新建订单，xid:{}",xid);
        // 订单新建时默认初始状态是0
        order.setStatus(0);
        int result = orderMapper.insertSelective(order);
        // 写入数据库成功后，获得插入mysql的实体对象
        Order orderFromDB = null;
        if(result > 0) {
            // 从mysql中查询刚插入的记录
            orderFromDB = orderMapper.selectOne(order);
            log.info("------------新建订单成功，订单信息为：{}",orderFromDB);
            System.out.println();
            // 2.扣减库存
            log.info("------------开始扣减库存，做扣减count");
            storageFeignApi.decrease(orderFromDB.getProductId(),orderFromDB.getCount());
            log.info("------------扣减库存成功");
            System.out.println();
            // 3.扣减账户余额
            log.info("------------开始扣减余额，做扣减money");
            accountFeignApi.decrease(orderFromDB.getUserId(),orderFromDB.getMoney());
            log.info("------------扣减余额成功");
            System.out.println();
            // 4.修改订单状态，从0到1，1代表已完成
            log.info("------------开始修改订单状态");
            orderFromDB.setStatus(1);
            // Example 构造器, where条件
            Example whereCondition = new Example(Order.class);
            Example.Criteria criteria = whereCondition.createCriteria();
            criteria.andEqualTo("userId",orderFromDB.getUserId());
            criteria.andEqualTo("status",0);
            int updateResult = orderMapper.updateByExampleSelective(orderFromDB, whereCondition);
            log.info("------------修改订单状态成功,updateResult:{}",updateResult);
        }
        System.out.println();
        log.info("------------结束新建订单，xid:{}",xid);
    }
}
